<!--
 * @Author: wjk
 * @Date: 2020-12-04 14:25:21
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-24 18:40:31
 * @description: 素材圈个人中心
-->
<template>
  <base-page-view v-if="userData" class-name="page-container material-user-center">
    <!-- #ifndef H5 -->
    <view :style="{opacity: scrollTop > statusBarHeight ? 1 : 0}">
      <base-nav title="个人主页" left-icon-pic="icon_arror_left" :nav-holder="false" :background="scrollTop > statusBarHeight ? 'white' : 'transparent'" left-icon="back" nav-position="fixed" :left-click="handleLeftClick"></base-nav>
    </view>
    <!-- #endif -->
    <view class="top-user" :style="{ 'background-image': `url(${imgAssets}/bg_user_center.png)` }">
      <view class="material-user-center-nav-bar" :style="'padding-top: ' + statusBarHeight + 'px;'">
        <view class="left-part" :style="'top: ' + (statusBarHeight + 22) + 'px;'" @click="handleLeftClick">
          <!-- 导航栏左边 -->
          <image class="nav-icon click-active" :src="`/static/images/icon/icon_return.png`" mode="aspectFit" />
        </view>
        <!-- #ifndef H5 -->
        <view class="title-part">
          <!-- 导航栏中间 -->
          <view class="nav-title">{{ '个人主页' }}</view>
        </view>
        <!-- #endif -->
      </view>
      <view class="user-box">
        <view class="user-img">
          <b-image :src="userData.head_img_url" is-head width="120" height="120" class-name="portrait" />
          <view class="user-sex">
            <image :src="`${imgAssets}/icon_gender_${userData.gender}.png`" />
          </view>
        </view>
        <view class="user-name">
          <view class="name-title">{{ userData.nick_name }}</view>
          <view class="time-title">加入碧选{{ userData.user_join_time }}天</view>
        </view>
        <view v-if="userData.is_attation === 0" class="edit" @click="toUserInfo">
          <view class="attention-les">编辑</view>
        </view>
        <view v-else class="edit" @click="attentionOperator">
          <view v-if="userData.is_attation === 1" class="attention-ned">已关注</view>
          <view v-if="userData.is_attation === 2" class="attention-les">+关注</view>
          <view v-if="userData.is_attation === 3" class="attention-ned">互相关注</view>
        </view>
      </view>
      <view class="user-alive-center">
        <view class="flex-box" @click="handelNavigateTo('/pagesMaterial/user-center/attention-list?type=myAttention')">
          <view class="nums">{{ userData.my_attention_num | formatNumber(2, true) }}</view>
          <view class="name">关注</view>
        </view>
        <view class="flex-box" @click="handelNavigateTo('/pagesMaterial/user-center/attention-list?type=getMyFans')">
          <view class="nums">{{ userData.attention_my_num | formatNumber(2, true) }}</view>
          <view class="name">粉丝</view>
        </view>
        <view class="flex-box" @click="handelNavigateTo('/pagesMaterial/user-center/praise-list')">
          <view class="nums">{{ userData.praise_num | formatNumber(2, true) }}</view>
          <view class="name">获赞</view>
        </view>
        <view class="flex-box" @click="handelNavigateTo('/pagesMine/collection/index')">
          <view class="nums">{{ userData.collect_num | formatNumber(2, true) }}</view>
          <view class="name">收藏</view>
        </view>
      </view>
    </view>
    <view class="sticky-wrapper tab-box" :style="{top: `${stickyHeight}px`}">
      <view class="tab-flex">
        <view class="tab-item" :class="{ active: tabCurrent === 1 }" @click="tabCurrent = 1">种草</view>
        <!-- #ifndef H5 -->
        <view class="tab-item" :class="{ active: tabCurrent === 2 }" @click="tabCurrent = 2">直播</view>
        <!-- #endif -->
        <view v-if="userData.is_attation === 0" class="tab-item" :class="{ active: tabCurrent === 3 }" @click="tabCurrent = 3">足迹</view>
      </view>
    </view>
    <view v-if="tabCurrent === 1" class="tab-container">
      <article-list :article-list="articleList" from-type="user-center" :is-my-self="userData.is_attation === 0" @refresh="fetchData(true)" @initShare="changeShareOption" />
      <base-list-state :list-length="listLength" :list-query="{page_no: listQuery.page_no, page_size: listQuery.page_size}" :list-state="listState" :list-empty="listEmpty" />
    </view>
    <view v-if="tabCurrent === 2" class="tab-container">
      <living-list ref="livingList" :user-id="listQuery.user_id" @getCommendData="getCommendData" @toLivingRoom="toLive" />
    </view>
    <view v-if="tabCurrent === 3" class="tab-container">
      <history-list ref="historyList" />
    </view>
    <block v-if="userData.is_attation === 0">
      <view v-if="tabCurrent === 1" class="publish-button" :class="{ active: showShareIcon }" @click="$navigateTo('/pagesMaterial/publish/index')">
        <b-image width="250" height="80" is-asset src="/static/images/material/icon_publish.png" />
      </view>
      <view v-if="tabCurrent === 2" class="publish-button" :class="{ active: showShareIcon }" @click="toLive('')">
        <b-image width="250" height="80" is-asset src="/static/images/material/icon_want_live.png" />
      </view>
    </block>
  </base-page-view>
</template>
<script>
import ArticleList from '@/pages/moments/components/article-list.vue'
import LivingList from './components/living-list.vue'
import HistoryList from './components/history-list.vue'
import './index.scss'
import { debounce } from '@/utils/tools'
import { navigateToMiniProgram, pageNavigateBack, h5NavigateTo } from '@/utils/navigateTo'
import { mapState } from 'vuex'
export default {
  components: {
    ArticleList,
    LivingList,
    HistoryList
  },
  data() {
    return {
      statusBarHeight: 20,
      stickyHeight: 0,
      imgAssets: Object.freeze(`${process.env.VUE_APP_IMAGE_ASSET}/images/material`),
      query: {},
      tabCurrent: 1,
      showShareIcon: true,
      scrollTop: 0,
      articleList: [],
      shareOption: {},
      userData: null,
      listQuery: {
        page_no: 1,
        page_size: 10,
        user_id: ''
      },
      listState: {
        loading: true,
        more: true
      },
      listEmpty: { type: 'empty_list', text: '暂无数据' }
    }
  },
  computed: {
    listLength() {
      // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.articleList.length
    },
    ...mapState(['token', 'userInfo'])
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
    this.showShareIcon = false
    clearInterval(this.shareTimer)
    this.shareTimer = setTimeout(() => {
      this.showShareIcon = true
    }, 500)
  },
  onPullDownRefresh() {
    this.listQuery.page_no = 1
    this.fetchData()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 500)
  },
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  onShow() {
    this.statusBarHeight = this.$statusBarHeight
    // #ifndef H5
    this.stickyHeight = this.statusBarHeight + 44
    // #endif
    if (this.articleList.length === 0) {
      this.listQuery.page_no = 1
    }
    this.fetchData(this.articleList.length > 0)
  },
  onLoad(option) {
    this.query = { ...option }
    this.listQuery.user_id = this.query.materialUserId || (this.userInfo ? this.userInfo.uid : '')
  },
  onReachBottom: debounce(function() {
    switch (this.tabCurrent) {
      case 1:
        if (this.listState.more) {
          this.listQuery.page_no++
          this.fetchList()
        }
        break
      case 2:
        this.$refs.livingList && this.$refs.livingList.loadMore()
        break
      case 3:
        this.$refs.historyList && this.$refs.historyList.loadMore()
        break
      default:
        break
    }
  }, 500),
  methods: {
    async fetchData(updateFlag) {
      const res = await this.$api.materialApi.getMyHome({
        user_id: this.listQuery.user_id
      })
      if (res.success) {
        this.userData = res.data
        this.fetchList(updateFlag)
        this.initShare()
      }
    },
    changeShareOption(res) {
      this.shareOption = res
    },
    async fetchList(updateFlag) {
      const listQuery = { ...this.listQuery }
      if (updateFlag) {
        listQuery.page_no = 1
        listQuery.page_size = this.articleList.length
      }
      this.listState.loading = true
      const res = await this.$api.materialApi.getUserList(listQuery)
      if (res.success) {
        if (listQuery.page_no === 1) {
          this.articleList = []
          this.listState.more = true
        }
        this.articleList = this.articleList.concat(res.data)
        if (res.data.length < listQuery.page_size) {
          this.listState.more = false
        }
        this.listState.loading = false
      }
    },
    async fetchHistoryList() {
      this.listState.loading = true
      const res = await this.$api.materialApi.getViewHistory(this.listQuery)
      if (res.success) {
        if (this.listQuery.page_no === 1) {
          this.historyList = []
          this.listState.more = true
        }
        this.historyList = this.historyList.concat(res.data)
        if (res.data.length < this.listQuery.page_size) {
          this.listState.more = false
        }
        this.listState.loading = false
      }
    },
    async attentionOperator() {
      if (!this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      const operatorType = this.userData.is_attation === 2 ? 1 : 0
      const res = await this.$api.materialApi.attentionOperator({
        operatorType,
        userId: this.listQuery.user_id
      })
      if (res.success) {
        this.userData.is_attation = res.data.attentionStatus
        uni.showToast({
          title: this.userData.is_attation === 2 ? '取消关注成功' : '关注成功',
          icon: 'none',
          duration: 2000
        })
      }
    },
    handelNavigateTo(url) {
      if (this.userData.is_attation !== 0) return
      this.$navigateTo(url)
    },
    toUserInfo() {
      this.$navigateTo('/pagesMine/user-info/index')
    },
    getCommendData(type) {
      this.hasLivingList = type
    },
    toLive(item) {
      console.log('item', item)
      let path = ''
      if (item) {
        path = `/pagesDetail/living-room/index?roundId=${item.id}`
      } else {
        path = '/pagesDetail/living-list/index'
        console.log('this.hasLivingList', this.hasLivingList)
        if (!this.hasLivingList) {
          h5NavigateTo('https://mp.weixin.qq.com/s/OyaDs1cbrkRO6nJZqbgBPA')
          return
        }
      }
      console.log('path', path)
      navigateToMiniProgram({
        extraData: {
          toPath: path,
          platform: 'minProgram-bx'
        },
        success: () => {
          this.$store.dispatch('setExtraData', null)
        },
        fail: err => {
          console.log(err)
        }
      })
    },
    // 分享初始化
    initShare() {
      if (this.token && this.userData) {
        this.shareOption = {
          share_title: this.userData.nick_name,
          share_url: '',
          share_image: this.userData.head_img_url || '',
          share_icon: this.userData.head_img_url || '',
          share_content: '快来围观我的主页，更多惊喜好礼等着你',
          share_list: [
            {
              pic: this.userData.head_img_url,
              titleArr: [this.userData.nick_name]
            }
          ]
        }
        this.showShare()
      } else {
        this.hideShare()
      }
    },
    handleLeftClick() {
      pageNavigateBack()
    }
  }
}
</script>
